package com.example.demo.service.comm;

import com.example.demo.entity.exception.EnumException;
import com.example.demo.entity.exception.EnumResult;
import com.mongodb.BasicDBObject;
import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * @description:
 * @author: cj
 * @create: 17-03-14 17:58:14
 */
@Component
public class MongodbService {

    //    @Resource
//    ConnectionString connectionString;

    @Value("${spring.data.mongodb.database}")
    String dataBaseName;
    @Resource
    MongoClient mongoClient;

    MongoDatabase database;
    @Resource
    MongoTemplate mongoTemplate;

    public MongodbService() {
//        if (database == null) {
//            database = mongoClient.getDatabase( connectionString.getDatabase() );
//        }
    }

    @PostConstruct
    public void setDatabase() {
        if (database == null) {
            database = mongoClient.getDatabase( dataBaseName );
        }
    }

    /**
     * 修改
     *
     * @param collectionName 表名
     * @param updateMap      修改的map (_id 是必须填写的)
     * @return 修改
     */
    public Map<String, Object> update(String collectionName, Map<String, Object> updateMap) {
        try {
            BasicDBObject queryDb = new BasicDBObject( "_id", new ObjectId( updateMap.get( "_id" ).toString() ) );
            updateMap.put( "_id", new ObjectId( updateMap.get( "_id" ).toString() ) );
            BasicDBObject updateDb = new BasicDBObject( updateMap );
            database.getCollection( collectionName )
                    .updateMany( queryDb, new BasicDBObject( "$set", updateDb ) );
        } catch (Exception e) {
            e.printStackTrace();
            throw new EnumException( EnumResult.EX_FAIL_CODE );
        }
        return updateMap;
    }


}
